// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.unit;

/**
 * Tests, that indexing is faster
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class ConditionVsIndexBenchmark {
  private final static int CYCLES = 35000000 * 4;
  
  public void testCond() {
    int reg1 = 1;
    int reg2 = 1;
    boolean regsetbool = false;
    int temp = 0;
    int cycles = CYCLES;
    while (cycles-- != 0) {
      if (regsetbool) {
        temp += reg1;
      } else {
        temp += reg2;
      }     

      regsetbool = !regsetbool;
    }
    //System.out.println("Results: " + temp);
  }
  
  public void testSwitch() {
    int reg1 = 1;
    int reg2 = 1;
    int regset = 0;
    int temp = 0;
    int cycles = CYCLES;
    while (cycles-- != 0) {
      switch (regset) {
        case 0:
          temp += reg1;
          break;
        case 1:
          temp += reg2;
          break;
      }     

      regset ^= 1;
    }
    //System.out.println("Results: " + temp);
  }
  
  public void testIndex() {
    final int[] regs = new int[] {1, 1};
    int regset = 0;
    int cycles = CYCLES;
    int temp = 0;
    while (cycles-- != 0) {
      temp += regs[regset];
      regset ^= 1;
    }
    //System.out.println("Results: " + temp);
  }
  
  public static void main(String[] args) {
    ConditionVsIndexBenchmark benchmark = new ConditionVsIndexBenchmark();
    long time;

    benchmark.testSwitch();
    time = System.currentTimeMillis();
    benchmark.testSwitch();
    System.out.println("Switch: " + (System.currentTimeMillis() - time) + "ms");
    
    benchmark.testCond();
    time = System.currentTimeMillis();
    benchmark.testCond();
    System.out.println("Cond: " + (System.currentTimeMillis() - time) + "ms");

    benchmark.testIndex();
    time = System.currentTimeMillis();
    benchmark.testIndex();
    System.out.println("Index: " + (System.currentTimeMillis() - time) + "ms");
  }
}
